"""FAQ 它是一个提供相关功能的模块."""
from typing import List

from fastapi import Request
from sqlalchemy import select

from core.database import db_session
from core.exception import AlertException
from core.models import Faq, FaqMaster
from service import BaseService


class FaqService(BaseService):
    """
    提供FAQ相关服务的相关性注入类。
    """

    def __init__(self, request: Request, db: db_session):
        self.request = request
        self.db = db

    def raise_exception(self, status_code: int = 400, detail: str = None, url: str = None):
        raise AlertException(detail, status_code, url)

    def fetch_faq_master(self, fm_id: int) -> FaqMaster:
        """
        FAQ 分类 1我们在数据库中查找枪.
        """
        return self.db.get(FaqMaster, fm_id)

    def fetch_faq_masters(self) -> List[FaqMaster]:
        """
        FAQ 在数据库中查找分类列表.
        """
        return self.db.scalars(
            select(FaqMaster).order_by(
                FaqMaster.fm_order.asc(),
                FaqMaster.fm_id.asc()
            )
        ).all()

    def fetch_faqs(self, faq_master: FaqMaster, stx: str = None) -> List[Faq]:
        """
        FAQ 我把名单拿出来.
        """
        query = faq_master.related_faqs.order_by(Faq.fa_order.asc())
        if stx:
            query = query.where(
                Faq.fa_subject.like(f"%{stx}%")
                | Faq.fa_content.like(f"%{stx}%")
            )
        return self.db.scalars(query).all()

    def read_faq_masters(self) -> List[FaqMaster]:
        """
        FAQ 我们提出了一个分类器列表.
        """
        faq_masters = self.fetch_faq_masters()
        if not faq_masters:
            self.raise_exception(404, "FAQ未注册.")
        return faq_masters

    def read_faq_master(self, fm_id: int) -> FaqMaster:
        """
        FAQ 提出了分类.
        """
        faq_master = self.fetch_faq_master(fm_id)
        if not faq_master:
            self.raise_exception(404, f"{fm_id} : FAQ 分类信息不存在.")
        return faq_master

    def read_faqs(self, faq_master: FaqMaster, stx: str = None) -> List[Faq]:
        """
        FAQ 我把名单拿出来.
        """
        faqs = self.fetch_faqs(faq_master, stx)
        return faqs
